package com.zsp.utils.security_jwt;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

@Component // 将工具类注册为 Spring 容器中的 Bean
public class SecurityUtils {

    // 获取当前用户的 Authentication 对象
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    // 获取当前用户对象(UserLogin)的json字符串
    public static String getUser() {
        Authentication authentication = getAuthentication();
        if (authentication != null || authentication.getPrincipal() instanceof User) {
            User user = (User) authentication.getPrincipal();
            return user.getUsername(); // 返回用户,因为在filter那里已经把用户给塞进去了，塞到了用户名那里
        }
        return null; // 如果用户未登录或认证信息为空，返回 null
    }
}
